# -*- coding: utf-8 -*- 
"""
========================================================================================================================
@project : my-sanic
@file: myListener
@Author: mengying
@email: 652044581@qq.com
@date: 2023/3/3 13:36
@desc: 我的监听器, 监听服务启动或者关闭
========================================================================================================================
"""
import logging
import os
from pathlib import Path, PurePath

from addict import Dict
from sanic import Sanic

from config import config
from database import commons
from middleware.myInitProject import InitProject
from utils.myCache import Cache
from utils.myMongo import MongoConfig, AsyncMongoClient

app = Sanic.get_app(config.PROJECT_NAME)


@app.listener('before_server_start')
async def setup_db(app, loop):
    # 配置mongodb数据库
    if hasattr(config, "MONGO_HOST"):
        mongoConfig = Dict()
        mongoConfig.host = config.MONGO_HOST
        mongoConfig.port = config.MONGO_PORT
        mongoConfig.username = config.MONGO_USER
        mongoConfig.password = config.MONGO_PASSWORD
        mongoConfig.db = config.MONGO_DB
        mongoConfig: Dict = mongoConfig.to_dict()
        MongoConfig(*tuple(mongoConfig.values()))
        # 获取数据库的链接实例
        commons.db = AsyncMongoClient()

    # 配置redis缓存组件
    if hasattr(config, 'REDIS_HOST'):
        cacheConfig = Dict()
        cacheConfig.mode = "async"  # redis的同步还是异步
        cacheConfig.host = config.REDIS_HOST
        cacheConfig.port = config.REDIS_PORT
        cacheConfig.db = config.REDIS_DB
        cacheConfig.password = config.REDIS_PASSWORD
        app.ctx.redisCache = Cache(cacheConfig.to_dict()).select("redis").current_db

    logging.info("server setup db successfully")


@app.listener('after_server_start')
async def notify_server_started(app, loop):
    # 内置初始化项目的相关配置
    await InitProject.run()

    logging.info("server has started successfully")

    # 服务启动LOGO
    banner = Path.joinpath(PurePath(__file__).parent, 'myBuddha.txt')
    if os.path.exists(banner):
        with open(banner, "r", encoding="utf-8") as f:
            print(f.read())


@app.listener('before_server_stop')
async def notify_server_stopping(app, loop):
    logging.info('Server shutting down!')


@app.listener('after_server_stop')
async def close_db(app, loop):
    logging.info('Server shutting down!')
